package org.example.servlet;

import org.example.DAO.LikeDAO;
import org.example.entity.Like;
import org.example.DAO.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

@WebServlet("/blog/like")
public class BlogLikeServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession(false);

        // 1. 校验登录状态
        if (session == null || session.getAttribute("userId") == null) {
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            resp.getWriter().write("用户未登录");
            return;
        }
        Integer userId = (Integer) session.getAttribute("userId");

        // 2. 获取参数
        String blogId = req.getParameter("blogId");
        String typeParam = req.getParameter("type");
        if (blogId == null || typeParam == null) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().write("参数缺失");
            return;
        }
        boolean likeType = Boolean.parseBoolean(typeParam);

        // 3. 数据库操作
        try (Connection conn = DBUtil.getConnection()) {
            LikeDAO likeDAO = new LikeDAO(conn);

            // 检查当前点赞状态
            Boolean existingType = likeDAO.getUserBlogLikeStatus(userId, blogId);
            if (existingType != null) {
                if (existingType.equals(likeType)) {
                    // 取消点赞
                    likeDAO.deleteLikeByUserAndBlog(userId, blogId);
                    resp.getWriter().write("取消成功");
                } else {
                    // 切换点赞类型（先删旧，再加新）
                    likeDAO.deleteLikeByUserAndBlog(userId, blogId);
                    likeDAO.addLike(new Like(userId, blogId, likeType));
                    resp.getWriter().write("切换成功");
                }
            } else {
                // 新增点赞
                likeDAO.addLike(new Like(userId, blogId, likeType));
                resp.getWriter().write("操作成功");
            }
        } catch (SQLException e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().write("服务器错误：" + e.getMessage());
        }
    }
}